package com.tanhua.interceptor;

import com.itheima.commons.utils.JwtUtils;
import com.tanhua.model.domain.User;
import io.jsonwebtoken.Claims;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@ControllerAdvice
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token，进行解析和封装到threadLocal
        String token = request.getHeader("Authorization");
        //网关进行鉴权操作
//        boolean b = JwtUtils.verifyToken(token);
//        if (!b) {
//            response.setStatus(401);
//            return false;
//        }
        Claims claims = JwtUtils.getClaims(token);
        String mobile = claims.get("mobile").toString();
        Integer id = (Integer) claims.get("id");

        User user = new User();
        user.setId(Long.valueOf(id));
        user.setMobile(mobile);

        UserHolder.set(user);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}
